<template>
  <div class="main">
    <div class="content">
      <div class="com_main">
            <div class="com-title">
                <div class="com-title_lable"></div>
                <div class="title-text">基础设置</div>
            </div>
            <el-form class="mr20 mt20 ml20" :model="list" ref="form" label-width="124px" :rules="rules">
                <el-row type="flex" :gutter="80" class="flex-wrap">
                <el-col :span="24">
                    <el-form-item prop="name" label="模板名称">
                    <el-input v-model="list.name" placeholder="模板名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item prop="bianma" label="模板编码">
                    <el-input v-model="list.bianma" placeholder="模板编码"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="dictVal" label="模板分类">
                    <pl-dict v-model="dictValue" dictType="VISUAL_DEV_TYPE"></pl-dict>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="模板类型">
                    <el-radio-group v-model="list.radio" @input="radioChange">
                      <el-radio-button label="1">普通表单</el-radio-button>
                      <el-radio-button label="2">列表页面</el-radio-button>
                    </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="模板说明">
                      <el-input v-model="list.description" type="textarea" :rows="4" resize="none"/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="数据来源">
                      <el-select v-model="list.sourceVal" placeholder="请选择" class="width-100" @change="changeSource">
                        <el-option v-for="item in source" :key="item.value" :label="item.label" :value="item.value" ></el-option>
                      </el-select>
                    </el-form-item>
                </el-col>
                <el-col>
                  <el-button type="primary" @click="addSelectDialog" v-show="showSelectDialog" class="showSelectDialog">添加视图</el-button>
                  <el-button type="primary" @click="chooseDb" v-show="DbShow" class="showSelectDialog">选择数据库</el-button>
                  <el-tag style="margin-left: 10px;" v-show="DbName != ''">{{ DbName }}</el-tag>
                </el-col>
                <el-col :span="24">
                  <el-table :data="tableData" header-row-class-name="tab-header" style="width: 100%;color: #606266;" empty-text="点击“新增”可选择1条(单表)或2条以上(多表)">
                    <el-table-column prop="index" label="序号" width="60">
                    </el-table-column>
                    <el-table-column prop="typeId" label="类别" width="60">
                      <template slot-scope="scope">
                        <el-tag v-if="scope.row.typeId=='1'">主表</el-tag>
                        <el-tag type="warning" v-else @click="changeTable(scope.row.index)"
                          style="cursor:pointer" title="点击设置成主表">从表</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column prop="tableName" label="表名" width="200">
                    </el-table-column>
                    <el-table-column prop="columns" label="外键字段" width="200">
                      <template slot-scope="scope" v-if="scope.row.typeId != '1'">
                        <el-select v-model="scope.row.val1" :disabled="showSelectDialog" placeholder="请选择">
                          <el-option v-for="item in scope.row.columns" :key="item.columnName"
                            :label="item.columnName" :value="item.columnName">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="relationField" label="关联主键" width="200">
                      <template slot-scope="scope" v-if="scope.row.typeId != '1'">
                        <el-select v-model="scope.row.val2" :disabled="showSelectDialog" placeholder="请选择">
                          <el-option v-for="item in scope.row.relationField" :key="item.columnName"
                            :label="item.columnName" :value="item.columnName">
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="操作">
                      <template slot-scope="scope">
                        <el-button size="mini" type="text" class="remove"
                          @click="delItem(scope.$index)">移除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <div class="addTable" @click="openTableBox()">
                    <el-button type="text" icon="el-icon-plus">新增一行</el-button>
                  </div>
                  <div class="btn">
                    <el-button @click="hideForm()">取消</el-button>
                    <el-button @click="dataFormSubmit()" type="primary">保存</el-button>
                  </div>
                </el-col>
                </el-row>
            </el-form>
            <el-dialog title="数据选择" :visible.sync="dialogVisible" width="720px" class="select-w100" :modal='showModal'>
              <el-form class="mr40" label-width="60px" :model="list">
                <el-col :span="12">
                  <el-form-item prop="" label="关键词">
                    <el-input v-model="search" suffix-icon="iconfont pointer icon-xuanze color-77" placeholder="请输入关键词查询"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item style="margin-left:20px;" label-width="20px">
                    <el-button type="primary" icon="el-icon-search" @click="initData()">查询</el-button>
                    <el-button icon="el-icon-refresh-right" @click="refresh()">重置</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-table ref="multipleTable" :data="dialogTableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="index" label="序号" width="120"></el-table-column>
                    <el-table-column prop="tableName" label="表名" width="200"></el-table-column>
                    <el-table-column prop="remarks" label="说明" show-overflow-tooltip></el-table-column>
                  </el-table>
                  <el-pagination
                    class="text-center mt10"
                    @size-change="sizeChangeHandle"
                    @current-change="currentChangeHandle"
                    :current-page="pageBean.currentPage"
                    :page-sizes="[5, 10,]"
                    :page-size="pageBean.pageSize"
                    :total="pageBean.totalPage"
                    layout="total, sizes, prev, pager, next, jumper"
                  >
                  </el-pagination>
                </el-col>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button class="dialog_btn" @click="dialogCancel">取 消</el-button>
                <el-button type="primary" @click="dialogConfirm" >确 定</el-button>
              </span>
            </el-dialog>
            <el-dialog title="数据库选择" :visible.sync="dbVisible" width="720px" class="select-w100" :modal='showModal'>
              <el-form class="mr40" label-width="60px" :model="DbList">
                <el-col :span="24">
                  <el-table @select="selectRow" ref="dbDialogTable" :data="dbTableData" style="width: 100%">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column type="index" width="100" label="序号"></el-table-column>
                    <el-table-column prop="dbName" label="数据库名"></el-table-column>
                  </el-table>
                  <el-pagination
                    class="text-center mt10"
                    @size-change="sizeChangeHandle"
                    @current-change="currentChangeHandleDb"
                    :current-page="db.currentPage"
                    :page-sizes="[5, 10,]"
                    :page-size="db.pageSize"
                    :total="db.totalPage"
                    layout="total, sizes, prev, pager, next, jumper"
                  >
                  </el-pagination>
                </el-col>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button class="dialog_btn" @click="dbVisible = false">取 消</el-button>
                <el-button type="primary" @click="DbConfirm" >确 定</el-button>
              </span>
            </el-dialog>
            <view-select-dialog ref="viewSelectDialogRef" @confirmDialog="viewSelectCallback"></view-select-dialog>
        </div>
    </div>
    <!-- <info-form></info-form> -->
  </div>
</template>

<script>
import devFormService from "@/service/dev/DevFormService";
import viewSelectDialog from "../dialog/ViewSelect.vue";
import plDict from "@/plugin/pl-base/pl-dict"
import viewCdesigner from '@/mixins/viewCdesigner';

export default {
  components:{
    viewSelectDialog,
    plDict
  },
  mixins:[viewCdesigner],
  props:['editData'],
  data(){
    return{
      dialogVisible:false,
      dbVisible:false,
      list: {
        name:'',
        bianma:'',
        radio:'1',
        description:'',
        sourceVal:''
      },
      DbList:{},
      DbChooseData:{},
      listData: [{ mc1: "1", mc2: "", mc3: "", mc4: "", mc5: "" }],
      activeName: "first",
      options: [],
      activeName: "first",
      tableData:[],
      dbTableData:[],
      dialogTableData:[],
      source: [{
          value: 1,
          label: '数据库'
        }, {
          value: 2,
          label: '视图'
        }
      ],
      rules: {
          name: [
            { required: true, message: '模板名称不能为空', trigger: 'blur' }
          ],
          bianma: [
            { required: true, message: '模板编码不能为空', trigger: 'blur' }
          ],
          dictval:[
            { required: true, message: '模板分类不能为空', trigger: 'change' }
          ]
        },
      multipleSelection:[],
      pageBean:{},
      db:{},
      search:'',
      dictValue:'',
      showModal:false,
      showSelectDialog:false,
      DbShow:false,
      editId:'',
      databaseid:'',
      DbName:'',
      checkedOption: [], //选中选项
      resId:''
    }
  },
  watch:{ 
    'editData':function(val) {
      console.log(val,'val');
      this.list.name = val.fullName;
      this.list.bianma = val.enCode;
      // this.list.radio = val.fullName;
      this.list.description = val.description;
      this.dictValue = val.category;
      this.list.radio = val.state || 1;
      this.list.sourceVal = val.type || '';
      if(val.type == 2){
        this.showSelectDialog = true;
      }else if(val.type == 1){
        this.showSelectDialog = false;
        this.DbShow = true;
        this.DbName = val.interfaceName
      }
      if(val.temTable && val.type == 1){
        let table = JSON.parse(val.temTable);
        let relationField = [];
        console.log(table,'111');
        table.forEach((item,index) => {
          let param = {
            tablename: item.tableName,
            databaseid: val.dbLinkId
          }
          devFormService.queryListColumn(param).then((res)=>{
            this.$set(item,'columns' , res.data)
            if(index == 0){
              relationField = res.data
            }
            this.$set(item,'relationField' , relationField)
          })
        });
        this.tableData = table;
        console.log(this.tableData,'tableData');
      }else if(val.type == 2){
        let table = JSON.parse(val.temTable);
        this.tableData = table;
      }
      this.editId = val.id || '';
      this.databaseid = val.dbLinkId || '';
    }, 
  },
  created(){
    var str=location.href;
    this.resId = str.split('formList/')[1];
  },
  methods:{
    openTableBox(){
      if(this.showSelectDialog){
        return
      }
      console.log(this.list);
      if(this.list.sourceVal == ''){
        this.$message({
          message: '请先选择数据来源',
          type: 'warning'
        });
        return
      }
      this.dialogVisible = true;
      let param = {
        currentPage:1,
        // pageSize:5,
        databaseid:this.databaseid
      }
      this.getTablePage(param)
    },
    sizeChangeHandle(e){
      this.pageBean.pageSize = e;
      let param = {
        currentPage:this.pageBean.currentPage,
        pageSize:e,
        databaseid:this.databaseid
      }
      this.getTablePage(param)
    },
    currentChangeHandle(e){
      this.pageBean.currentPage = e;
      let param = {
        currentPage:e,
        pageSize:this.pageBean.pageSize,
        databaseid:this.databaseid
      }
      this.getTablePage(param)
    },
    handleSelectionChange(val){
      this.multipleSelection = val;
    },
    dialogCancel(){
      this.multipleSelection = [];
      this.dialogVisible = false;
    },
    dialogConfirm(){
      let that = this;
      this.multipleSelection.forEach(async(item,index) => {
          if(that.tableData.length > 0){
            item.index = that.tableData.length + 1
          }else{
            item.index = ++index;
          }
          item.typeId = item.index;
          let param = {
            tablename: item.tableName,
            databaseid: this.databaseid
          }
          let resp =  await devFormService.queryListColumn(param)
          item.columns = [];
          item.relationField = [];
          that.$set(item,'columns' , resp.data)
          if(that.tableData.length != 0){
            that.$set(item,'relationField' , that.tableData[0].columns)
          }else if(that.multipleSelection.length != 0){
            that.$set(item,'relationField' , that.multipleSelection[0].columns)
          }
          that.$set(item,'val1' , '')
          that.$set(item,'val2' , '')
          that.tableData.push(item)
      });
      setTimeout(()=>{
        that.tableData = that.arrSort(that.tableData,'index');
      },300)
      this.multipleSelection = [];
      this.dialogVisible = false;
    },
    delItem(ix){
      if(this.showSelectDialog){
        return
      }
      this.tableData.splice(ix,1);
      this.tableData.forEach((item,index) => {
          item.index = ++index;
          item.typeId = item.index;
      });
    },
    changeTable(ix){
      let index = ix - 1;
      this.tableData.forEach((item) => {
          if(item.typeId == 1){
            // item.typeId = 2
            this.$delete(item,'typeId')
            this.$set(item,'typeId',2)
          }
      });
      this.$delete(this.tableData[index],'typeId')
      this.$set(this.tableData[index],'typeId',1)
      console.log(this.tableData,'tableData');
      // this.tableData[index].typeId = 1;
    },
    initData(){
      this.pageBean.currentPage = 1;
      this.pageBean.pageSize = 10;
      let param = {
        currentPage:1,
        pageSize:10,
        databaseid:this.databaseid,
        tablename:this.search
      }
      this.getTablePage(param)
    },
    refresh(){
      this.search = '';
      let param = {
        currentPage:1,
        pageSize:10,
        databaseid:this.databaseid
      }
      this.getTablePage(param)
    },
    getTablePage(param){
      let that = this;
      devFormService.getTablePage(param).then((res)=>{
        console.log(res,'resssss');
        let data = res.data.data;
        if(data){
          data.forEach((item,index) => {
            item.index = ++index;
          });
        }
        that.dialogTableData = data;
        that.pageBean.totalPage = res.data.totalCount
      })
    },
    arrSort(arr,property){
      return arr.sort(function(a,b){
        const val1 = a[property];
        const val2 = b[property];
        return val1 -val2
      })
    },
    hideForm(){
      this.tableData = [];
      this.showSelectDialog = false;
      this.$refs.form.clearValidate();
      this.clearList();
      this.$parent.hideForm();
    },
    getDataList(){
      this.$parent.getDataList()
    },
    dataFormSubmit(){
      if(!this.list.name){
        this.$message({
          message: '模板名称不能为空',
          type: 'warning'
        });
        return
      }
      if(!this.list.bianma){
        this.$message({
          message: '模板编码不能为空',
          type: 'warning'
        });
        return
      }
      if(!this.dictValue){
        this.$message({
          message: '模板分类不能为空',
          type: 'warning'
        });
        return
      }
      if(this.tableData.length == 0){
        this.$message({
          message: '请至少选择一个数据表',
          type: 'warning'
        });
        return
      }
      this.saveForm()
    },
    saveForm(){
      let table = this.tableData;
      console.log(table,'table');
      table.forEach((item,index)=>{

      })
      table = JSON.stringify(table)

      console.log(this.dictValue);
      if(this.editData.formData && JSON.parse(this.editData.formData).fields){
        this.formData.fields = JSON.parse(this.editData.formData).fields
      }
      if(this.editData.formData){
        this.formData.idGlobal = JSON.parse(this.editData.formData).idGlobal
      }
      let param = {
        description:this.list.description,
        enCode:this.list.bianma,
        temTable:table,
        category:this.dictValue,
        fullName:this.list.name,
        state:this.list.radio,
        type:this.list.sourceVal,
        dbLinkId:this.databaseid,
        id:this.editData.id,
        interfaceName:this.DbName,
        columnData: JSON.stringify(this.columnData),
        formData: JSON.stringify(this.formData),
        resId:this.resId
      };
      console.log(this.formData,'save.formdata');
      devFormService.save(param).then(()=>{
        this.hideForm();
        this.getDataList();
      })
    },
    clearList(){
      this.list = {
        name:'',
        bianma:'',
        radio:'1',
        description:'',
        sourceVal:''
      };
      this.dbVisible = false;
      this.DbShow = false;
      this.DbName = '';
    },
    async viewSelectCallback(val){
      let obj = {};
      console.log(val,'val');
      obj.tableCat = '';//表类别
      obj.schemaName = val[0].orgAlias;
      obj.tableName = val[0].linkTable;
      obj.tableType = '';
      obj.remarks = val[0].name;
      obj.typeCat = val[0].type;
      obj.typeSchem = '';
      obj.typeName = '';
      obj.pks = val[0].viewField;
      obj.indexes = 1;
      obj.typeId = 1;
      obj.val1 = val[0].userAlias;
      obj.val2 = val[0].viewField;
      this.databaseid = val[0].datasource;
      this.tableData = [];
      this.clearData();
      devFormService.getInitMasterData({viewId:val[0].id,status:val[0].status}).then((res)=>{
        obj.columns = [];
        for (let i = 0; i < res.data.attributes.length; i++) {
          let attrItem = res.data.attributes[i];
          let columnItem ={};
          columnItem["columnName"] = attrItem.code;
          columnItem["columnHumpName"] = attrItem.code;
          columnItem["remarks"] = attrItem.name;
          obj.columns.push(columnItem);
        }
        this.tableData.push(obj)
        this.convertJson(res.data,val[0])
      })
    },
    changeSource(val){
      console.log(this.tableData,'tabledata');
      this.tableData = [];
      this.clearData();
      if(val == 2){
        this.showSelectDialog = true;
        this.DbShow = false;
      }else if(val == 1){
        this.DbShow = true;
        this.showSelectDialog = false;
      }
    },
    addSelectDialog(){
      this.$refs['viewSelectDialogRef'].init('','')
    },
    chooseDb(data){
      this.tableData = [];
      this.dbVisible = true;
      let param = {
        currentPage:1,
        pageSize:5,
        status:1
      }
      if(data){
        param = data
      }
      devFormService.queryDbPage(param).then((res)=>{
        console.log(res,'resssss');
        this.dbTableData = res.data.data
        this.db.currentPage = res.data.currentPage
        this.db.pageSize = res.data.pageSize
        this.db.totalPage = res.data.totalCount
      })
    },
    currentChangeHandleDb(e){
      this.db.currentPage = e;
      let param = {
        currentPage:e,
        pageSize:this.db.pageSize,
        status:1
      }
      this.chooseDb(param)
    },
    DbConfirm(){
      if(this.DbChooseData){
        this.databaseid = this.DbChooseData.id;
        this.DbName = this.DbChooseData.dbName
      }
      this.dbVisible = false
    },
    radioChange(e){
      console.log(e,'eeeee');
    },
    /**
     * 单选
     */
      selectRow(selection,row) {
        this.DbChooseData = row;
        this.$refs.dbDialogTable.clearSelection();
        this.$refs.dbDialogTable.toggleRowSelection(row);
    },
  }
}
</script>

<style scoped>
  .main{
    /* height: calc(100% - 60px); */
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9;
  }
  .content{
    background-color: rgba(159, 159, 159, 0.3);
    padding-top: 20px;
    padding-bottom: 20px;
    height: 100%;
  }
    .com_main{
        width: 50%;
        margin: 0 auto;
        background-color: white;
        overflow: auto;
        overflow-x: hidden;
        border-radius: 4px;
    }
    .addTable{
      text-align: center;
      margin: 10px auto;
      border: 1px dashed #ebeef5;
    }
    .dialog_btn{
      margin-top: 20px;
    }
    .remove{
      color: red;
    }
    .com_main .from-font .el-form-item--mini.el-form-item, .com_main .el-form-item--small.el-form-item{
      margin-bottom: 20px;
    }
    .btn{
      display: flex;
      justify-content: flex-end;
    }
    .showSelectDialog{
      margin-left:124px;
      margin-bottom: 10px;
    }
</style>